<template>
  <div class="wrap">
    <div class="wrap-button" style="height: 28px">
      <div style="float: right">
        <a-select
          v-if="isSuperAdmin"
          placeholder="选择租户"
          v-model:value="recordSo.tenantId"
          style="width: 180px; margin-right: 8px"
          allowClear
          @change="handleChangeTenant"
        >
          <a-select-option v-for="item in tenants" :key="item.id" :value="item.id">{{
            item.name
          }}</a-select-option>
        </a-select>
        <a-select
          placeholder="选择项目"
          v-model:value="recordSo.projectId"
          style="width: 180px; margin-right: 8px"
          allowClear
          @change="handleChangeProject"
        >
          <a-select-option v-for="item in projects" :key="item.id" :value="item.id">{{
            item.name
          }}</a-select-option>
        </a-select>
        <a-select
          placeholder="选择设备"
          v-model:value="recordSo.deviceCode"
          style="width: 180px; margin-right: 8px"
          @change="handleChangeDevice"
        >
          <a-select-option v-for="item in devices" :key="item.code" :value="item.code">{{
            item.code
          }}</a-select-option>
        </a-select>
        <a-range-picker v-model:value="timePicker" style="margin-right: 8px" />
        <!-- <a-input
          v-model:value="keyword"
          style="width: 180px; margin-right: 8px"
          placeholder="输入关键字查询"
        >
          <template #prefix>
            <user-outlined />
          </template>
        </a-input> -->
        <a-button type="primary" style="margin-right: 8px" @click="list">查询</a-button>
        <a-button type="primary" @click="handleSearch">导出</a-button>
      </div>
    </div>
    <div style="flex: 1; margin-top: 16px">
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        :pagination="pagination"
        size="middle"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
        :showExpandColumn="false"
        :expandRowByClick="true"
        :expandedRowKeys="expandedRowKeys"
        :customRow="customRow"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'dataSource'">
            <a-tag v-if="record.dataSource === 1" color="cyan">开始</a-tag>
            <a-tag v-else-if="record.dataSource === 2" color="cyan">结束</a-tag>
            <a-tag v-else-if="record.dataSource === 3" color="cyan">暂停</a-tag>
            <a-tag v-else-if="record.dataSource === 4" color="cyan">段数据</a-tag>
            <a-tag v-else-if="record.dataSource === 5" color="cyan">定时</a-tag>
            <a-tag v-else color="red">未知</a-tag>
          </template>
          <template v-if="column.key === 'pileStatus'">
            <a-tag v-if="record.pileStatus === 1" color="cyan">停钻</a-tag>
            <a-tag v-else-if="record.pileStatus === 2" color="cyan">下钻</a-tag>
            <a-tag v-else-if="record.pileStatus === 3" color="cyan">提钻</a-tag>
            <a-tag v-else-if="record.pileStatus === 4" color="cyan">复下</a-tag>
            <a-tag v-else-if="record.pileStatus === 5" color="cyan">复提</a-tag>
            <a-tag v-else color="red">未知</a-tag>
          </template>
          <template v-if="column.key === 'slurSta'">
            <a-tag v-if="record.pileStatus === 0" color="cyan">不喷浆</a-tag>
            <a-tag v-else-if="record.pileStatus === 1" color="cyan">喷浆</a-tag>
            <a-tag v-else color="red">未知</a-tag>
          </template>
          <template v-if="column.key === 'operation'"> </template>
        </template>
        <template #expandedRowRender="{ record }">
          <p style="margin: 0">
            {{ record.pileNo }}
          </p>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, onMounted, reactive, watch, computed } from 'vue'
  import {
    DeleteOutlined,
    SettingOutlined,
    EditOutlined,
    EllipsisOutlined,
  } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  import type { TreeProps } from 'ant-design-vue'
  import { BaseTitle } from '/@/components/Title'
  import { listRole, addRole, deleteRole, listPermission, setPermission } from '/@/api/sys/role'
  import { listTenant } from '/@/api/sys/tenant'
  import { TenantModel } from '/@/api/sys/model/tenantModel'
  import { listProject } from '/@/api/pd/project'
  import { ProjectListResult } from '/@/api/pd/model/projectModel'
  import { listDevice } from '/@/api/pd/device'
  import { DeviceListResult, DeviceListSO } from '/@/api/pd/model/deviceModel'
  import { listDeviceRecord } from '/@/api/pd/deviceRecord'
  import { DeviceRecordResult, DeviceRecordSo } from '/@/api/pd/model/deviceRecordModel'
  import { Modal } from 'ant-design-vue'
  import Echarts from '/@/components/ReEcharts/index.vue'
  import { EChartsOption } from 'echarts'
  import type { Dayjs } from 'dayjs'
  import { useUserStore } from '/@/store/modules/user'

  const open = ref<boolean>(false)
  const openPermission = ref<boolean>(false)
  const loading = ref(false)
  const showBaseFlag = ref(true)
  const hideText = ref('收起')
  const value1 = ref('a')
  const expandedRowKeys = ref<string[]>([])
  type RangeValue = [Dayjs, Dayjs]
  const timePicker = ref<RangeValue>()
  const tenants = ref<TenantModel[]>([])
  const projects = ref<ProjectListResult[]>([])
  const devices = ref<DeviceListResult[]>([])
  const userStore = useUserStore()
  const isSuperAdmin = userStore.getSuperAdmin

  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 15,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })

  // const recordSo = computed(() => ({
  //   deviceCode: '',
  //   machCode: '',
  //   startTime: '',
  //   endTime: '',
  //   tenantId: '',
  // }))

  let recordSo = reactive<DeviceRecordSo>({
    deviceCode: undefined,
    machCode: undefined,
    startTime: undefined,
    endTime: undefined,
    tenantId: isSuperAdmin ? undefined : userStore.getUserInfo.tenantId,
    projectId: undefined,
  })
  // let deviceSO = reactive<DeviceListSO>({
  //   tenantId: undefined,
  //   projectId: undefined,
  // })

  const deviceSO = computed(() => ({
    tenantId: recordSo.tenantId,
    projectId: recordSo.projectId,
  }))

  const pageParam = computed(() => ({
    query: recordSo,
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))

  const columns = [
    {
      title: '桩编码',
      dataIndex: 'pileNo',
      key: 'pileNo',
      align: 'center',
      width: 140,
      fixed: 'left',
    },
    {
      title: '数据来源',
      dataIndex: 'dataSource',
      key: 'dataSource',
      align: 'center',
      width: 80,
    },
    {
      title: '桩状态',
      dataIndex: 'pileStatus',
      key: 'pileStatus',
      align: 'center',
      width: 80,
    },
    {
      title: '喷浆状态',
      dataIndex: 'slurSta',
      key: 'slurSta',
      align: 'center',
      width: 80,
    },
    {
      title: '倾角x',
      dataIndex: 'angleX',
      key: 'angleX',
      align: 'center',
      width: 80,
    },
    {
      title: '倾角y',
      dataIndex: 'angleY',
      key: 'angleY',
      align: 'center',
      width: 80,
    },
    {
      title: '垂直度',
      dataIndex: 'vert',
      key: 'vert',
      align: 'center',
      width: 80,
    },
    {
      title: '实时钻杆电流(A)',
      dataIndex: 'cur',
      key: 'cur',
      align: 'center',
      width: 120,
    },
    {
      title: '实时压力(Mpa)',
      dataIndex: 'pressure',
      key: 'pressure',
      align: 'center',
      width: 80,
    },
    {
      title: '实时流量(L/Min)',
      dataIndex: 'flow',
      key: 'flow',
      align: 'center',
      width: 140,
    },
    {
      title: '实时密度(g/cm³)',
      dataIndex: 'density',
      key: 'density',
      align: 'center',
      width: 140,
    },
    {
      title: '实时速度(cm/min)',
      dataIndex: 'speed',
      key: 'speed',
      align: 'center',
      width: 140,
    },
    {
      title: '实时段灰量(kg)',
      dataIndex: 'segAsh',
      key: 'segAsh',
      align: 'center',
      width: 140,
    },
    {
      title: '实际桩长(m)',
      dataIndex: 'pileDepth',
      key: 'pileDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '初搅深度(m)',
      dataIndex: 'firDepth',
      key: 'firDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '复搅深度(m)',
      dataIndex: 'secDepth',
      key: 'secDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '空搅深度(m)',
      dataIndex: 'emDepth',
      key: 'emDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '当前深度(m)',
      dataIndex: 'curDepth',
      key: 'curDepth',
      align: 'center',
      width: 140,
    },
    {
      title: '累计空搅浆量(L)',
      dataIndex: 'emSlur',
      key: 'emSlur',
      align: 'center',
      width: 140,
    },
    {
      title: '累计空搅灰量(kg)',
      dataIndex: 'emAsh',
      key: 'emAsh',
      align: 'center',
      width: 140,
    },
  ]

  let data = ref<DeviceRecordResult[]>([])

  let checkedKeys = ref<string[]>(['3'])

  interface Props {
    width?: string
    height?: string
    option: EChartsOption
  }
  const props = withDefaults(defineProps<Props>(), {
    width: '100%',
    height: '100%',
    option: () => ({}),
  })

  watch(checkedKeys, () => {
    console.log('checkedKeys', checkedKeys)
  })
  watch(timePicker, () => {
    recordSo.startTime = timePicker.value?.[0]?.format('YYYY-MM-DD 00:00:00')
    recordSo.endTime = timePicker.value?.[1]?.format('YYYY-MM-DD 23:59:59')
    list()
  })
  //#endregion

  onMounted(() => {
    list()
    if (isSuperAdmin) initTenant()
    initProject()
    initDevice()
    console.log('isSuperAdmin', isSuperAdmin)
  })

  async function list() {
    loading.value = true
    const res = await listDeviceRecord(pageParam.value)
    console.log('res', res)
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  function handleTableChange(page) {
    pagination.value.current = page.current
    list()
  }

  function initTenant() {
    listTenant().then((res) => {
      tenants.value = res
    })
  }

  function initProject() {
    recordSo.projectId = undefined
    listProject(recordSo.tenantId).then((res) => {
      projects.value = res
    })
  }

  function initDevice() {
    recordSo.deviceCode = undefined
    listDevice(deviceSO.value).then((res) => {
      devices.value = res
    })
  }
  // const initTenant = () => {

  // }

  //#region 用户

  const hideBaseInfo = () => {
    showBaseFlag.value = !showBaseFlag.value
    hideText.value = showBaseFlag.value ? '收起' : '展开'
  }

  const customRow = (record) => {
    return {
      onClick: () => {
        if (record.id == expandedRowKeys.value[0]) {
          expandedRowKeys.value = []
        } else {
          expandedRowKeys.value = [record.id]
        }
      },
    }
  }

  const handleChangeTenant = () => {
    initProject()
    initDevice()
    list()
  }
  const handleChangeProject = () => {
    initDevice()
    list()
  }
  const handleChangeDevice = () => {
    list()
  }

  //#endregion
</script>

<style lang="scss" scoped>
  .wrap {
    max-width: calc(100vw - 230px);
    &-table {
      margin-top: 16px;
    }
  }

  .base-enter-active,
  .base-leave-active {
    transition: opacity 0.4s;
  }
  .base-enter,
  .base-leave-active {
    opacity: 0;
  }
</style>
